const Jwt = require('jsonwebtoken')
const { createConnection } = require('mysql')
const config = require('../config')

function tokenVerify(token) {
  try {
    Jwt.verify(token, config.token.secretKey)
    return true
  } catch (error) {
    return false
  }
}

module.exports = {
  isValidToken(req, res, next) {
    // console.log(req.body);
    let bearerToken = req.headers.authorization
    if (bearerToken) {
      let token = bearerToken.split(' ')[1]
      const a = tokenVerify(token)
      if (tokenVerify(token)) {
        next()
      } else {
        res.send({
          code: 403,
          message: '登录凭证无效,请重新登录!',
        })
      }
    } else {
      res.send({
        code: 401,
        message: '请登录后重试',
      })
    }
  },
}
